
import 'dart:convert' as convert;
import 'dart:developer';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';

import '../config/app_url_address.dart';




///Log Interceptor
class MyInterceptor extends Interceptor {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    LogUtilDH.print(
        'Request URL: ${options.uri} Request Parameters: ${options.data} Request Headers: ${options.headers}');

    return handler.next(options);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    String errorStr = "\n==================== DioLogInterceptor onError ====================";
    // "- URL:\n${err.request.baseUrl + err.request.path}\n"
    // "- METHOD: ${err.request.method}\n";
    if (err.response != null && err.response?.data != null) {
      print('╔ ${err.type.toString()}');
      errorStr += "- ERROR: ${_parseResponse(err.response!)}\n";
    } else {
      errorStr += "- ERRORTYPE: ${err.type}\n";
      errorStr += "- MSG: ${err.message}\n";
    }
    LogUtilDH.print(errorStr);
    return handler.next(err);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    String responseLogContent = "\n==================== RESPONSE ====================\n"
        "- STATUS: ${response.statusCode}\n";
    // "- URL:\n${response.request.uri}\n";
    /*responseStr += "- HEADER:\n{";
    response.headers.forEach(
        (key, list) => responseStr += "\n  " + "\"$key\" : \"$list\",");
    responseStr += "\n}\n";*/
    // responseStr += "- STATUS: ${response.statusCode}\n";
    RequestOptions requestOptions=response.requestOptions;
    responseLogContent += "Return data interface address is: \n";
    responseLogContent += requestOptions.baseUrl+requestOptions.path+"\n";
    responseLogContent += "The following is the returned data content: \n";
    LogUtilDH.print(responseLogContent);

    String responseStr="";
    if (response.data != null) {
      if (response.data is String) {
        responseStr += "${response.data}";
      } else {
        responseStr += "${convert.jsonEncode(response.data)}";
      }
    }
    LogUtilDH.print(responseStr);
    LogUtilDH.print("\n==================== RESPONSE END ====================\n");
    handler.next(response);
  }

  String _parseResponse(Response response) {
    String responseStr = "";
    var data = response.data;
    if (data is Map)
      responseStr = convert.jsonEncode(data);
    else if (data is List)
      responseStr =convert.jsonEncode(data);
    else
      responseStr = response.data.toString();
    return responseStr;
  }
}



class LogUtilDH{

  static print(String message){
    if(debugMode){
      log(message);
    }
  }
}
